package com.kmsoft.security.filter;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Component
public class JwtTokenOncePerRequestFilter extends OncePerRequestFilter {

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        String token = null;
        String bearerToken = request.getHeader("Authorization");
//        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
//            token = bearerToken.substring(7);
//        }
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            try {
//                if (token != null && Jwt.verify(token)) {
//                    Authentication auth = Jwt.getAuthentication(token);
//                    if (auth != null) {
//                        SecurityContextHolder.getContext().setAuthentication(auth);
//                    }
//                }
                // 校验token
                if ("abc".equals(bearerToken)) {
                    User userDetails = new User("username", "password", new ArrayList<>());
                    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()));
                }
            } catch (Exception e) {
                logger.error("解析token失败", e);
            }
        }
        filterChain.doFilter(request, response);
    }

}
